<template>
  <div>
    <!---搜索表单-->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="关键字">
              <el-input
                style="width: 100%"
                v-model="searchObj.keyword"
                placeholder="用户名、姓名、手机号码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="date"
                type="daterange"
                range-separator="To"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" @click="handleSeachSysUsers" size="small">
            搜索
          </el-button>
          <el-button @click="handleClear" size="small">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <!--添加按钮-->
    <div class="tools-div">
      <el-button type="success" size="small" @click="handleShowAddDialog">
        添 加
      </el-button>
    </div>
    <!---数据表格-->
    <div>
      <el-table :data="list" style="width: 100%">
        <el-table-column prop="userName" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="手机" />
        <el-table-column prop="avatar" label="头像" #default="scope">
          <img :src="scope.row.avatar" width="50" />
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" #default="scope">
          {{ scope.row.status == 1 ? '正常' : '停用' }}
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column
          label="操作"
          align="center"
          width="280"
          #default="scope"
        >
          <el-button
            type="primary"
            size="small"
            @click="handleShowEditDialog(scope.row.id)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            type="warning"
            size="small"
            @click="handleShowAssignRoleDialog(scope.row)"
          >
            分配角色
          </el-button>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页导航 -->
    <div>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
    <!-- 新增/修改 用户的对话框 -->
    <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
      <el-form label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="sysUser.userName" />
        </el-form-item>
        <el-form-item v-if="!sysUser.id" label="密码">
          <el-input v-model="sysUser.password" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="sysUser.name" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="sysUser.phone" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :headers="headers"
            :data="{ module: 'avatar' }"
          >
            <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="sysUser.description" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSaveOrUpdateSysUser">
            提交
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog v-model="assignRoleDialogVisible" title="分配角色">
      <el-form>
        <el-form-item label="用户名" label-width="120px">
          <el-input v-model="userName" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色列表" label-width="120px">
          <el-checkbox-group v-model="checkedRoleIds">
            <el-checkbox
              v-for="sysRole in sysRoles"
              :key="sysRole.id"
              :label="sysRole.id"
              :checked="sysRole.checked"
            >
              {{ sysRole.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssignRoles">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  GetSysUserPage,
  DelById,
  SaveSysUser,
  GetById,
  UpdateById,
  AssignRoles,
} from '@/api/sysUser'
import { GetAllSysRoles } from '@/api/sysrole'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApp } from '@/pinia/modules/app'
/* 分配角色 */
let userName = ref('')
let userId = ref(null)
let assignRoleDialogVisible = ref(false)
let checkedRoleIds = ref([])
let sysRoles = ref([])
//显示分配角色的对话框
const handleShowAssignRoleDialog = async row => {
  // checkedRoleIds.value = []
  //row代表点击分配角色按钮所在行的 用户json对象
  userName.value = row.userName
  userId.value = row.id
  //  弹出对话框之前  将数组置空，否则有缓存
  sysRoles.value = []
  checkedRoleIds.value = []
  //查询所有的角色列表回显
  const { data } = await GetAllSysRoles(row.id)
  sysRoles.value = data
  console.log(sysRoles.value, checkedRoleIds)
  assignRoleDialogVisible.value = true
}
//分配角色对话框
const handleAssignRoles = async () => {
  //获取点击分配角色按钮所在行用户的id
  //获取选中角色列表的id集合
  //提交请求
  await AssignRoles(userId.value, checkedRoleIds.value)
  //关闭对话框
  assignRoleDialogVisible.value = false

  console.log(checkedRoleIds.value)
}

/* 分配角色end */
/*
  更新用户
*/
const handleShowEditDialog = async id => {
  //使用id查询要回显的用户信息
  const { data } = await GetById(id)
  //回显:查询到的数据赋值给表单双绑的对象
  sysUser.value = data
  //显示对话框
  dialogVisible.value = true
}
const handleUpdateSysUser = async () => {
  await UpdateById(sysUser.value)
  //更新成功
  dialogVisible.value = false
  fetchData()
}
/*
  更新用户end
*/
const handleSaveOrUpdateSysUser = () => {
  if (sysUser.value.id) {
    //更新
    handleUpdateSysUser()
  } else {
    //新增
    handleSaveSysUser()
  }
}
//===========新增用户

let dialogVisible = ref(false)
let uploadUrl = ref('http://localhost:8501/admin/system/file/upload')
const sysUser = ref({
  avatar: '',
})
const handleShowAddDialog = () => {
  //重置数据
  sysUser.value = {}
  dialogVisible.value = true
}

const handleSaveSysUser = async () => {
  //提交新增用户的请求
  await SaveSysUser(sysUser.value)
  ElMessage.success('保存成功')
  //关闭对话框
  dialogVisible.value = false
  //刷新页面
  fetchData()
}

// 配置登录token请求头的属性
const headers = ref({
  token: useApp().authorization.token,
})

//==上传文件成功后的回调函数
const handleUploadSuccess = response => {
  console.log('handleUploadSuccess', response)
  sysUser.value.avatar = response.data
}

//-----------新增用户end

//== 删除按钮事件函数
const handleDelete = row => {
  ElMessageBox.confirm(`您确认要删除用户【${row.userName}】吗?`, 'Warning', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      //点击确认按钮
      await DelById(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      //刷新页面数据
      fetchData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}

//搜索表单参数
const searchObj = ref({
  keyword: '',
  createTimeStart: '',
  createTimeEnd: '',
})
let date = ref('')
// 表格数据模型
const list = ref([])

// 分页条数据模型
let total = ref(0)
let pageNum = ref(1)
let pageSize = ref(3)
//钩子函数
onMounted(() => {
  fetchData()
})
//条件查询
const handleSeachSysUsers = () => {
  //console.log(date.value[0], date.value[1], searchObj.value)
  //封装查询条件
  searchObj.value.createTimeStart = date.value[0]
  searchObj.value.createTimeEnd = date.value[1]
  fetchData()
}
//清空条件查询
const handleClear = () => {
  searchObj.value = {
    keyword: '',
    createTimeStart: '',
    createTimeEnd: '',
  }
  pageNum.value = 1
  pageSize.value = 3
  fetchData()
}
//查询分页数据
const fetchData = async () => {
  const { data } = await GetSysUserPage(
    searchObj.value,
    pageNum.value,
    pageSize.value
  )
  total.value = data.total
  list.value = data.list
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
